package com.xianniu.ltc.controller;

import cn.devezhao.commons.web.ServletUtils;
import cn.devezhao.commons.web.WebUtils;
import cn.devezhao.persist4j.engine.ID;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONAware;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.rebuild.api.RespBody;
import com.rebuild.core.UserContextHolder;
import com.rebuild.core.configuration.general.DataListManager;
import com.rebuild.utils.JSONUtils;
import com.rebuild.web.BaseController;
import com.rebuild.web.user.signup.LoginController;
import com.xianniu.ltc.model.po.*;
import com.xianniu.ltc.model.vo.XnAccountTeamVO;
import com.xianniu.ltc.model.vo.XnLeadTeamVO;
import com.xianniu.ltc.service.XnAccountTeamService;
import com.xxl.sso.core.entity.ReturnT;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @author WangRuiJie
 * @Title: AccountTeamController
 * @Package com.xianniu.ltc.controller
 * @Description: 客户组管理
 * @date 2021/6/172:55 下午
 */
@RestController
@Slf4j
@RequestMapping(value = "/accountTeam")
public class XnAccountTeamController extends BaseController {

    @Autowired
    private XnAccountTeamService xnAccountTeamService;

    /**
     * 后台客户组-查询客户组列表
     * @return
     */
    @GetMapping("/selectAccountTeamForAdmin")
    public ModelAndView selectAccountTeamForAdmin(HttpServletRequest request) {
        final ID user = getRequestUser(request);
        String tenantCode = (String) ServletUtils.getSessionAttribute(request, LoginController.TENANT_CODE);
        UserContextHolder.setTenant(tenantCode);
        ModelAndView mv = createModelAndView("/xianniu/admin/account/account-team");
        mv.getModel().put("entityName", "XnAccountTeam");
        mv.getModel().put("entityLabel", "客户池");
        mv.getModel().put("entityIcon", "entityIcon");
        JSON config = DataListManager.instance.getFieldsLayout("XnAccountTeam", user, tenantCode);
        mv.getModel().put("DataListConfig", JSON.toJSONString(config));
        return mv;
    }

    /**
     * 新前端调用返回JSON：后台客户组-查询客户组列表
     * @return
     */
    @GetMapping("/selectAccountTeamForAdmin-new")
    public JSONAware selectAccountTeamForAdminNew(HttpServletRequest request) {
        final ID user = getRequestUser(request);
        String tenantCode = (String) ServletUtils.getSessionAttribute(request, LoginController.TENANT_CODE);
        UserContextHolder.setTenant(tenantCode);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("entityName", "XnAccountTeam");
        jsonObject.put("entityLabel", "客户池");
        jsonObject.put("entityIcon", "entityIcon");
        JSON config = DataListManager.instance.getFieldsLayout("XnAccountTeam", user, tenantCode);
        jsonObject.put("DataListConfig", JSON.toJSONString(config));
        return jsonObject;
    }

    /**
     * 下拉框-查询客户组列表
     * @param po
     * @return
     */
    @PostMapping("/accountTeamSelector")
    public JSONAware accountTeamSelector(@RequestBody QueryAccountTeamAdminPO po, HttpServletRequest request) {
        String tenantCode = (String) ServletUtils.getSessionAttribute(request, LoginController.TENANT_CODE);
        UserContextHolder.setTenant(tenantCode);
        log.info("后台线索组-后台查询客户组列表:{}", JSON.toJSON(po));
        IPage<XnAccountTeamVO> voiPage = xnAccountTeamService.selectAccountTeamForAdmin(po);
        JSONObject json = new JSONObject();
        json.put("pageList", voiPage);
        return json;
    }

    /**
     * 后台客户组-新增客户组
     * @param po
     * @return
     */
    @PostMapping("/addAccountTeamForAdmin")
    public JSONAware addAccountTeamForAdmin(@RequestBody AddXnAccountTeamPO po , HttpServletRequest request){
        String tenantCode = (String) ServletUtils.getSessionAttribute(request, LoginController.TENANT_CODE);
        UserContextHolder.setTenant(tenantCode);
        log.info("后台客户组-新增客户组:{}", JSON.toJSON(po));
        if(Objects.isNull(po.getHeadBy()) || Objects.isNull(po.getUseDept())){
            return RespBody.errorl("负责人，使用部门不能为空");
        }
        ID currentUser = (ID) ServletUtils.getSessionAttribute(request, WebUtils.CURRENT_USER);
        po.setCreatedBy(currentUser.toString());
        ReturnT returnT = xnAccountTeamService.addAccountTeamForAdmin(po);
        if (returnT.getCode() != 200){
            return RespBody.errorl(returnT.getMsg());
        }
        return RespBody.ok();
    }

    /**
     * 后台客户组-转移分组
     * @param po
     * @return
     */
    @PostMapping("/transferAccountTeamForAdmin")
    public JSONAware transferAccountTeamForAdmin(@RequestBody TransferAccountTeamPO po, HttpServletRequest request) {
        if (StringUtils.isEmpty(po.getFromAccountTeamId()) || StringUtils.isEmpty(po.getToAccountTeamId())){
            return RespBody.errorl("PlsSet1FieldShowLeast");
        }
        String tenantCode = (String) ServletUtils.getSessionAttribute(request, LoginController.TENANT_CODE);
        UserContextHolder.setTenant(tenantCode);
        log.info("后台客户组-转移分组:{}", JSON.toJSON(po));
        ReturnT returnT = xnAccountTeamService.transferAccountTeamForAdmin(po);
        if (returnT.getCode() != 200){
            return RespBody.errorl(returnT.getMsg());
        }
        return RespBody.ok();
    }


    /**
     * 后台客户组-修改分组
     * @param po
     * @return
     */
    @PostMapping("/updateAccountTeamForAdmin")
    public JSONAware updateAccountTeamForAdmin(@RequestBody UpdateAccountTeamPO po, HttpServletRequest request) {
        if (StringUtils.isEmpty(po.getMetadata().getId())){
            return RespBody.errorl("PlsSet1FieldShowLeast");
        }
        String tenantCode = (String) ServletUtils.getSessionAttribute(request, LoginController.TENANT_CODE);
        UserContextHolder.setTenant(tenantCode);
        ID currentUser = (ID) ServletUtils.getSessionAttribute(request, WebUtils.CURRENT_USER);
        po.setModifiedBy(currentUser.toString());
        log.info("后台客户组-修改分组:{}", JSON.toJSON(po));
        ReturnT returnT = xnAccountTeamService.updateAccountTeamForAdmin(po);
        if (returnT.getCode() != 200){
            return RespBody.errorl(returnT.getMsg());
        }
        return RespBody.ok();
    }

    /**
     * 后台-根据ID删除客户组
     * @param id
     * @return
     */
    @GetMapping("/deleteAccountTeamForAdmin")
    public JSONAware deleteAccountTeamForAdmin(String id, HttpServletRequest request) {
        String tenantCode = (String) ServletUtils.getSessionAttribute(request, LoginController.TENANT_CODE);
        UserContextHolder.setTenant(tenantCode);
        log.info("后台-根据ID删除客户组:{}", JSON.toJSON(id));
        ReturnT returnT = xnAccountTeamService.deleteAccountTeamForAdmin(id);
        if (returnT.getCode() != 200){
            return RespBody.errorl(returnT.getMsg());
        }
        return RespBody.ok();
    }
}
